﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace TextFileSplitter
{
    public class Splitter
    {
        private string _filePath;

        public Splitter(string filePath)
        {
            if (filePath == null)
                throw new ArgumentNullException("filePath");

            _filePath = filePath;
        }

        public void Split(int blockSize, bool shouldKeepWholeLine)
        {
            string mainFileName = Path.GetFileNameWithoutExtension(_filePath);
            string fileExtension = Path.GetExtension(_filePath);

            using (StreamReader reader = new StreamReader(_filePath))
            {
                int index = 0;
                char[] leftBuffer = null;

                while (!reader.EndOfStream)
                {
                    char[] buffer = new char[blockSize];
                    int validBufferLength = reader.ReadBlock(buffer, 0, buffer.Length);
                    int invalidLength = 0;

                    if (shouldKeepWholeLine)
                    {
                        // Make buffer end with a new line
                        for (int i = buffer.Length - 1; i >= 0; i--, invalidLength++)
                        {
                            if (buffer[i] == '\n')
                            {
                                validBufferLength = i + 1;
                                break;
                            }
                        }
                    }

                    using (StreamWriter writer = new StreamWriter(mainFileName + (++index) + fileExtension))
                    {
                        // Save unsaved buffer from previous file
                        if (leftBuffer != null)
                        {
                            writer.Write(leftBuffer, 0, leftBuffer.Length);
                            leftBuffer = null;
                        }

                        writer.Write(buffer, 0, validBufferLength);
                    }

                    // Keep unsaved buffer
                    if (invalidLength > 0)
                    {
                        leftBuffer = new char[invalidLength];
                        Array.Copy(buffer, validBufferLength, leftBuffer, 0, leftBuffer.Length);
                    }
                }
            }
        }
    }
}
